package org.example.security.component;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.db.entity.Permission;
import org.example.db.mapper.PermissionMapper;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class DynamicSecurityService {

    PermissionMapper permissionMapper;

    public DynamicSecurityService(PermissionMapper permissionMapper) {
        this.permissionMapper = permissionMapper;
    }

    public Map<String, ConfigAttribute> getAllPermissions(){

        Map<String, ConfigAttribute> result = new ConcurrentHashMap<>();
        List<Permission> permissions = permissionMapper.selectList(null);

        for(Permission permission: permissions){

            result.put(permission.getUrl(),
                    new org.springframework.security.access.SecurityConfig(permission.getId() + ":" + permission.getName()));

        }
        return result;
    }

    public org.springframework.security.access.SecurityConfig getAdminConfigAttribute(){

        Permission adminPermission = permissionMapper.selectList(
                new QueryWrapper<Permission>().lambda().eq(Permission::getUrl, "*")).get(0);

        return new org.springframework.security.access.SecurityConfig(adminPermission.getId() + ":" + adminPermission.getName());
    }
}
